package com.qkun.library.base;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.qkun.library.utils.MyLog;
import com.qkun.library.utils.Utils;

public abstract class LazyFragment extends BaseFragment {

    private static final String TAG = "LazyFragment";

    private boolean mIsPrepared;

    //TODO：待采用其它最新解决方案
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        MyLog.d(TAG, "isVisibleToUser: " + getUserVisibleHint());
        if (getUserVisibleHint()) {
            onVisible();
        } else {
            onInvisible();
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = createView(inflater, container, savedInstanceState);
        if (Utils.nonNull(view)) {
            mIsPrepared = true;
            onLazy();
            return view;
        }
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    protected void onVisible() {
        onLazy();
    }

    protected void onInvisible() {
    }

    protected void onLazy() {
        if (!mIsPrepared || !getUserVisibleHint()) {
            return;
        }
        lazyLoad();
    }

    public boolean isPrepared() {
        return mIsPrepared;
    }

    protected abstract void lazyLoad();

    protected abstract View createView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState);
}
